import React, { useState, useEffect } from 'react';
import { Table, Pagination } from 'tea-component';
import { useSelector, useDispatch } from 'react-redux';
import * as actionTypes from '@src/model/actionType';
import { getQueryVariable } from '@src/utils/index';

const { autotip, scrollable } = Table.addons;

const DEFAULT_PAGE_INDEX = 1;
const DEFAULT_PAGE_SIZE = 5;

export default function NodeInfo(props) {
  const chainId = decodeURIComponent(getQueryVariable('chainid') || '');
  // @ts-ignore
  const homeStore = useSelector((state) => state.homeReducer);
  const dispatch = useDispatch();

  const [pageIndex, setPageIndex] = useState(DEFAULT_PAGE_INDEX);
  const [pageSize, setPageSize] = useState(DEFAULT_PAGE_SIZE);

  useEffect(() => {
    dispatch({ type: actionTypes.fetchNodeList, params: { Offset: pageIndex - 1, Limit: pageSize, ChainId: chainId } });
  }, [dispatch]);

  const onPagingChange = ({ pageIndex, pageSize }) => {
    setPageIndex(pageIndex);
    setPageSize(pageSize);
    dispatch({ type: actionTypes.fetchNodeList, params: { Offset: pageIndex - 1, Limit: pageSize, ChainId: chainId } });
  };
  return (
    <div
      style={{
        backgroundColor: '#fff',
        marginTop: '20px',
        border: '1px solid #DDDDDD',
      }}
    >
      <h5
        style={{
          fontSize: '14px',
          fontFamily: 'MicrosoftYaHei-Bold',
          color: '#444444',
          paddingTop: '14px',
          paddingLeft: '10px',
        }}
      >
        节点信息
      </h5>
      <Table
        style={{ width: '100%' }}
        verticalTop
        records={homeStore.nodeList.GroupList}
        recordKey="Id"
        bordered={false}
        columns={[
          {
            key: 'NodeId',
            header: '节点ID',
          },
          {
            key: 'NodeAddress',
            header: '节点端口',
            width: 350,
          },
          {
            key: 'BlockHeight',
            width: 150,
            header: '当前块高',
          },
          {
            key: 'Status',
            width: 100,
            header: '状态',
            // @ts-ignore
            render: (row) =>
              // @ts-ignore
              row.Status === 1 ? (
                <span style={{ color: '#0FC05E' }}>正常</span>
              ) : (
                <span style={{ color: '#EA6559' }}>异常</span>
              ),
          },
        ]}
        addons={[
          scrollable({
            maxHeight: 480,
          }),
          autotip({}),
        ]}
      />
      <Pagination
        recordCount={homeStore.nodeList.TotalCount}
        pageIndex={pageIndex}
        pageSize={pageSize}
        style={{ backgroundColor: '#fff', width: '100%', padding: '18px 14px' }}
        onPagingChange={onPagingChange}
        pageSizeOptions={[5]}
      />
    </div>
  );
}
